<?php
declare (strict_types=1);

namespace app\model;

use think\Model;
use think\model\relation\HasOne;
use utils\Auth;

/**
 * @mixin Model
 */
class Users extends Model
{
    //用户模型

    public function group(): HasOne
    {
        return $this->hasOne(UserGroup::class, 'id', 'user_group_id');
    }

    public function profile(): HasOne
    {
        return $this->hasOne(UserProfile::class, 'user_id', 'id');
    }

    public function getPasswordAttr($val)
    {
        if (request()->isLogin === false) return $val;
        $auth = new Auth();
        if ($auth->check('admin', request()->user->id)) {
            return $val;
        } else {
            return null;
        }
    }

    public function getCardAttr($val)
    {
        return substr($val,0, 10) . '********';
    }

    public function searchKeyAttr($query, $val, $data)
    {
        $query
            ->withJoin('profile')
            ->where('student_id|profile.name', 'like', '%' . $val . '%')
            ->select();
    }

    public static function login($data)
    {
        if ($data['type'] === 'h5') {
            $user = Users::where('card', $data['user'])->find();
        } elseif ($data['type'] === 'phone') {
            $user = Users::where('phone', $data['phone'])->find();
        }

        if (empty($user)) return false;
        if ($user->status !== 1) return false;
        if ($data['type'] === 'h5') {
            if (!password_verify($data['password'], $user->password)) return false;
        } elseif ($data['type'] === 'phone') {
            if (cache("login_sms_code_{$user->phone}") !== $data['code']) return false;
        }

        return true;
    }
}
